package p2pgame;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

// a few utility methods
public class Util {

	public static boolean logging=false;
	
	// Check if seed and hash(seed) matches
	public static boolean checkHash(int i,byte[] h){
		return (Arrays.equals(Util.hash(i),h));
	}

	public static byte[] hash(int number){
		return hash(Util.intToByteArray(number));
	}
	public static byte[] hash(byte[] number){
		MessageDigest md=null;
		try {
			md = MessageDigest.getInstance("SHA1");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return md.digest(number);
	}

	// xor byte arrays. The arrays must be of same length and the list must not be empty.
	public static byte[] xor(List<byte[]> list){
		byte[] result = list.get(0);
		for (int i = 1; i<list.size(); i++){
			result = xor(result, list.get(i));
		}
		return result;
	}
	public static byte[] xor (byte[] a, byte[] b){
		byte[] result = new byte[a.length];
		for (int i = 0; i<result.length; i++){
			result[i] = xor(a[i],b[i]);
		}
		return result;
	}
	public static byte xor(byte a, byte b){
		return (byte)((int)a^(int)b);
	}

	// no use for this at the moment
//	private int[] toIntArray(byte[] ba){
////	byte[] ba=id.toByteArray();
//	int[] result = new int[id.toByteArray().length/4];
//	int bytesPerInt = 4;
//	for(int i=0;i<result.length;i++){
//	int sum=0;
//	for(int j=0;j<bytesPerInt;j++){
//	sum+=ba[i*bytesPerInt+j]<<(j*8);
//	}
//	result[i]=sum;
//	}
//	return result;
//	}

	public static void log(String s){
		if ( Util.logging ){
			System.out.println(s);
		}
	}
	
	/**
	 * Returns a byte array containing the two's-complement representation of the integer.<br>
	 * The byte array will be in big-endian byte-order with a fixes length of 4
	 * (the least significant byte is in the 4th element).<br>
	 * <br>
	 * <b>Example:</b><br>
	 * <code>intToByteArray(258)</code> will return { 0, 0, 1, 2 },<br>
	 * <code>BigInteger.valueOf(258).toByteArray()</code> returns { 1, 2 }. 
	 * @param integer The integer to be converted.
	 * @return The byte array of length 4.
	 */
	public static byte[] intToByteArray (final int integer) {
		int byteNum = (40 - Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer)) / 8;
		byte[] byteArray = new byte[4];

		for (int n = 0; n < byteNum; n++)
			byteArray[3 - n] = (byte) (integer >>> (n * 8));

		return (byteArray);
	}
}
